package controller

import (
	"errors"
	"net/http"

	"github.com/kataras/iris"
	"github.com/kataras/iris/sessions"

	"im/common"
	"im/dao"
	"im/model"
	"im/requests"
)

type CollectionsController struct {
	Session *sessions.Session
	Ctx     iris.Context
	Base
}
func (c *CollectionsController) Get() {
	var (
		user   = c.Ctx.Values().Get("user").(model.Users)
		params = new(requests.CollectionsGetParams)
		list   = &[]model.Collections{}
		err    = c.Ctx.ReadJSON(params)
	)

	if err != nil {
		goto PARAMS_ERR
	}

	if params.Limit < 1 || params.Limit > 20 {
		err = errors.New("limit must between 1 and 20")
		goto PARAMS_ERR
	}

	list, err = dao.NewCollectionsDao().GetList(user.AppsId, user.Id, params.TextType)
	if err != nil {
		goto SQL_ERR
	}

	c.SendSmile(list)

PARAMS_ERR:
	c.Ctx.StatusCode(http.StatusBadRequest)
	c.SendCry("错误 " + err.Error())
	return

SQL_ERR:
	c.Ctx.StatusCode(http.StatusInternalServerError)
	c.SendCry("服务器发生错误 " + err.Error())
	return

}

func (c *CollectionsController) Post() {
	var (
		user   = c.Ctx.Values().Get("user").(model.Users)
		params = &model.Collections{}
		err    = c.Ctx.ReadJSON(params)
	)

	if err != nil {
		goto PARAMS_ERR
	}

	params.AppsId, params.UserId = user.AppsId, user.Id

	_, err = dao.NewCollectionsDao().Create(params)
	if err != nil {
		goto SQL_ERR
	}
	c.SendSmile(params.Id)
	return

PARAMS_ERR:
	c.Ctx.StatusCode(http.StatusBadRequest)
	c.Ctx.JSON(common.SendCry("错误 " + err.Error()))
	return

SQL_ERR:
	c.Ctx.StatusCode(http.StatusInternalServerError)
	c.Ctx.JSON(common.SendSad("服务器发生错误 " + err.Error()))
	return
}

func (c *CollectionsController) DeleteBy(id int64) {
	var (
		user = c.Ctx.Values().Get("user").(model.Users)
		num  int64
		err  error
	)

	num, err = dao.NewCollectionsDao().Delete(id, user.AppsId, user.Id)
	if err != nil {
		goto SQL_ERR
	}

	c.SendSmile(num)
	return

SQL_ERR:
	c.Ctx.StatusCode(http.StatusInternalServerError)
	c.SendCry("服务器发生错误 " + err.Error())
	return

}
